package com.freedom.monitor.myeye.config.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.thrift.TException;

import com.freedom.monitor.myeye.config.model.Count;
import com.freedom.monitor.myeye.config.utils.DbUtilsHelper;
import com.freedom.rpc.thrift.common.utils.Logger;

//用户服务，比如登录
public class ProductServiceImpl implements ProductServiceConfigService.Iface {
	private static final Logger logger = Logger.getLogger(ProductServiceImpl.class);


	@SuppressWarnings("unchecked")
	@Override
	public ServiceTemplateResult queryProductService(int page, int rows, String productId) throws TException {
		logger.debug("ConfigServiceImpl.queryServiceTemplateByProductId is invoked...");
		// 1)构造sql
		String sql = "select distinct id,serviceId,serviceName,serviceCode,";
		sql += " description,DATE_FORMAT(createTime,'%Y-%m-%d %k:%i:%s') as createTime,";
		sql += "totalCount,thresholdCount,";
		sql += "succeedRatioThreshold,averageTimeCostThreshold,";
		sql += "maxTimeCostThreshold,minTimeCostThreshold,";
		sql += "maxInvokedCount,minInvokedCount,";
		sql += "alarmPeriod ";
		sql += " from t_system_product_service_template ";
		sql += " where productId=?";
		sql += " order by createTime desc ";
		sql += " limit ?,?";
		logger.debug("sql ---> " + sql);
		// 2)开始查询
		List<com.freedom.monitor.myeye.config.model.ServiceTemplate> templates = (List<com.freedom.monitor.myeye.config.model.ServiceTemplate>) DbUtilsHelper
				.queryManyObject(sql, com.freedom.monitor.myeye.config.model.ServiceTemplate.class, productId,
						(page - 1) * rows, rows);
		if (null == templates) {// 修正一下
			templates = new ArrayList<com.freedom.monitor.myeye.config.model.ServiceTemplate>();
		}
		// 3)构造返回结果
		ServiceTemplateResult templateResult = new ServiceTemplateResult();
		templateResult.setSucceed(true);
		for (com.freedom.monitor.myeye.config.model.ServiceTemplate template : templates) {
			com.freedom.monitor.myeye.config.service.ServiceTemplate rpcTemplate = new com.freedom.monitor.myeye.config.service.ServiceTemplate();
			rpcTemplate.setId(template.getId());
			rpcTemplate.setServiceId(template.getServiceId());
			rpcTemplate.setServiceName(template.getServiceName());
			rpcTemplate.setServiceCode(template.getServiceCode());
			rpcTemplate.setDesc(template.getDescription());
			rpcTemplate.setCreateTime(template.getCreateTime());
			rpcTemplate.setTotalCount(template.getTotalCount());
			rpcTemplate.setThresholdCount(template.getThresholdCount());
			rpcTemplate.setSucceedRatioThreshold(template.getSucceedRatioThreshold());
			rpcTemplate.setAverageTimeCostThreshold(template.getAverageTimeCostThreshold());
			rpcTemplate.setMaxTimeCostThreshold(template.getMaxTimeCostThreshold());
			rpcTemplate.setMinTimeCostThreshold(template.getMinTimeCostThreshold());
			rpcTemplate.setAlarmPeriod(template.getAlarmPeriod());
			rpcTemplate.setMaxInvokedCount(template.getMaxInvokedCount());
			rpcTemplate.setMinInvokedCount(template.getMinInvokedCount());
			templateResult.addToServiceTemplateList(rpcTemplate);
		}
		// 再次修正
		if (null == templateResult.getServiceTemplateList()) {
			templateResult.setServiceTemplateList(new ArrayList<ServiceTemplate>());
		}
		// 5)设置总数
		sql = "select count(*) as count from t_system_product_service_template where productId=?";
		Count count = (Count) DbUtilsHelper.queryOneObject(sql, Count.class, productId);
		if (null != count) {
			templateResult.setTotal(count.getCount());
		} else {
			templateResult.setTotal(0);
		}
		// 5)返回结果
		logger.debug("return " + templateResult);
		return templateResult;
	}

	@Override
	public boolean addProductService(String serviceName, String serviceCode, int totalCount, int thresholdCount,
			int alarmPeriod, int succeedRatioThreshold, int averageTimeCostThreshold, int maxTimeCostThreshold,
			int minTimeCostThreshold, String desc, int maxInvokedCount, int minInvokedCount, String productId)
			throws TException {
		logger.debug("ConfigServiceImpl.addProductService invoked...");
		logger.debug("desc--->" + desc);
		if (null == desc) {
			desc = "";
		}
		try {
			// 1)构造sql
			String sql = "insert into t_system_product_service_template(productId,serviceId,serviceName,serviceCode,"
					+ "totalCount,thresholdCount," + "alarmPeriod,succeedRatioThreshold,"
					+ "averageTimeCostThreshold,maxTimeCostThreshold,"
					+ "minTimeCostThreshold,description,maxInvokedCount,minInvokedCount) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?) ";
			// 2)执行sql
			int result = DbUtilsHelper.insertOneObject(sql, productId, RandomStringUtils.random(64, true, true),
					serviceName, serviceCode, totalCount, thresholdCount, alarmPeriod, succeedRatioThreshold,
					averageTimeCostThreshold, maxTimeCostThreshold, minTimeCostThreshold, desc, maxInvokedCount,
					minInvokedCount);
			return (1 == result);
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public boolean editProductService(String serviceName, String serviceCode, int totalCount, int thresholdCount,
			int alarmPeriod, int succeedRatioThreshold, int averageTimeCostThreshold, int maxTimeCostThreshold,
			int minTimeCostThreshold, String desc, String serviceId, int maxInvokedCount, int minInvokedCount)
			throws TException {
		logger.debug("ConfigServiceImpl.editProductService invoked...");
		try {
			String sql = "update t_system_product_service_template " + "set serviceName=?," + "serviceCode=?,"
					+ "totalCount=?," + "thresholdCount=?," + "alarmPeriod=?," + "succeedRatioThreshold=?,"
					+ "averageTimeCostThreshold=?," + "maxTimeCostThreshold=?," + "minTimeCostThreshold=?,"
					+ "description=?, " + " maxInvokedCount=?,minInvokedCount=? " + "where serviceId=?";
			// 2)执行sql
			int result = DbUtilsHelper.updateOneObject(sql, serviceName, serviceCode, totalCount, thresholdCount, //
					alarmPeriod, succeedRatioThreshold, averageTimeCostThreshold, maxTimeCostThreshold, //
					minTimeCostThreshold, desc, maxInvokedCount, minInvokedCount, serviceId);
			return (1 == result);
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public boolean deleteProductService(String serviceId) throws TException {
		// 1)获得serviceId
		logger.debug("delete ProductService invoked...serviceId--->[" + serviceId + "]");
		// 2)构造sql
		String sql = "delete from t_system_product_service_template where serviceId=?";
		logger.debug("to be delete sql--->" + sql + " [" + serviceId + "]");
		// 3)执行sql
		int result = DbUtilsHelper.deleteOneObject(sql, serviceId.trim());
		logger.debug("result---" + result);
		return (1 == result);
	}

}
